import { observable, action, computed, runInAction } from 'mobx'
import { post, get } from 'lib/net'
import CommonVM from 'cvm/common'
import * as api from 'lib/constants/api'
import localforage from 'localforage'
import PostListVM from 'cvm/post/postlist'
import Toast from 'components/toast'
import wechat from 'lib/utils/wechat'

class NotifyItemVM {
  constructor (props) {
    this.data = props.data
  }

  @observable data = {}

  // 活动详情
  @action handleNotifyItem = () => {
    // localforage.setItem('postDetailId', item.ID, null)
    // .then(() => {
    //   this.context.router.history.push({pathname: '/mainText'})
    // })
  }
}

export default class HomeVM extends CommonVM {
  constructor (props) {
    super()
    this.props = props
    this.production()
  }

  // 是否签到
  @observable isSigned = 0
  // 活动通知
  @observable notify = []
  // 活动请求中
  @observable notifyLoading = false
  // 是否能下拉刷新
  @observable initializing = 0
  // 帖子列表模型
  @observable postListVM = null

  // 是否已签到
  @computed get signedInfo () {
    return this.isSigned === 1 ? '已签到' : '签到'
  }
  // 黑名单信息
  @computed get blankMsg () {
    return this.userInfo.isBlank === 1 ? '注意，由于您的行为不当，被关入小黑屋，您的评论发帖等功能都已关闭，截止时间' +
    this.userInfo.blankTime + '将恢复，如果有任何疑问，请到个人中心进行意见反馈，谢谢合作' : ''
  }
  // 加载中
  @computed get loading () {
    return this.notifyLoading
  }

  // 分享配置
  wxShareConfig = () => {
    let params = {
      appMessage: {
        title: '种植秀',
        link: api.WX_LOGIN,
        desc: '分享你的种植秀'
      },
      timeline: {
        title: '分享你的种植秀',
        link: api.WX_LOGIN
      }
    }
    wechat.wxShareConfig(params)
  }

  // 发布环境
  @action production = () => {
    if (this.userId) {
      this.fetchInit()
    } else {
      this.fetchSignin()
    }
    setTimeout(() => {
      this.wxShareConfig()
    }, 1000)
  }

  @action fetchInit = () => {
    this.postListVM = new PostListVM({data: this.props, api: api.GET_ALL_POST})
    this.fetchHomeNotify(this.userId)
    this.fetchIsSigned(this.userId)
  }

  // 本地环境
  @action development = () => {
    this.postListVM = new PostListVM({data: this.props, api: api.GET_ALL_POST})
    localforage.setItem('userInfo', {userId: 'AA516BC2-F101-48B9-B393-4C7B254E904C', isBlank: 0, blankTime: '2017-6-27 10:11:20'}, null)
    this.fetchHomeNotify('AA516BC2-F101-48B9-B393-4C7B254E904C')
    this.fetchIsSigned('AA516BC2-F101-48B9-B393-4C7B254E904C')
  }

  // 登录
  @action fetchSignin = async () => {
    Toast.loading(1, '正在授权')
    let code = this.props.history.location.search
    if (code.length > 10) {
      let res = await get(api.WX_ACCESS_TOKEN + code)
      if (!res.err) {
        let user = res.data
        let params = {
          OpenId: user.openid,
          Nickname: user.nickname,
          Sex: user.sex,
          City: user.city,
          Country: user.country,
          Province: user.province,
          Headimgurl: user.headimgurl
        }
        Toast.loading(1, '正在登录')
        let response = await post(api.ADD_USER, params)
        Toast.success('登录成功')
        if (response.state === 1) {
          let userInfo = {userId: response.data.UserInfoID, isBlank: response.data.Notalking, blankTime: response.data.NotalkingTime}
          localforage.setItem('userInfo', userInfo, null)
          this.saveUserInfo(userInfo)
          this.fetchInit()
        } else {
          Toast.fail('登录失败')
        }
      } else {
        Toast.fail('授权失败')
      }
    } else {
      Toast.fail('请使用微信登录')
    }
  }

  // 是否已签到
  @action fetchIsSigned = async () => {
    let params = { ID: this.userId }
    let res = await post(api.IS_SIGN_DATA, params)
    if (res.state === 1) {
      runInAction(() => {
        this.isSigned = res.data
      })
    }
  }

  // 是否能下拉
  @action handleScroll = () => {
    var viewTop = window.scrollY || window.pageYOffset || document.documentElement.scrollTop
    if (viewTop <= 0) {
      this.canRefresh = true
    } else {
      this.canRefresh = false
    }
  }

  // 下拉刷新
  @action handleRefresh = (resolve, reject) => {
    this.initializing = 2
  }

  // 获取首页活动通知
  @action fetchHomeNotify = async (userId) => {
    let params = {UserInfoID: userId}
    this.notifyLoading = true
    let res = await post(api.HOME_NOTIFY, params)
    if (res.state === 1) {
      runInAction(() => {
        if (res.data) {
          let data = res.data.map(item => {
            return new NotifyItemVM({data: item})
          })
          this.notify.splice(this.notify.length, 0, ...data)
        }
        this.notify = res.data
      })
    }
    this.notifyLoading = false
  }

  // 签到
  @action handleSign = async () => {
    if (this.isSigned) return
    let params = { ID: this.userId }
    let res = await post(api.SIGN_DATA, params)
    if (res.state === 1) {
      this.isSigned = 1
    } else {
      this.isSigned = 0
    }
  }
}
